<template>
  <page-card title="用户管理">
    <a-row type="flex">
      <a-col :span="5"
             :order="1">
        <div style="width:100%; overflow-x:auto">
          <slot name="unitTree" />
          <template v-if="!$slots.unitTree">
            <a-form layout="inline">
              <a-row>
                <a-col :span="24">
                  <a-input-search placeholder="机构名称、编码"
                                  v-model="unitNameOrCode"
                                  @search="findUnit(true)"
                                  style="min-width:200px;width: 100%"
                                  allow-clear />
                </a-col>
              </a-row>
            </a-form>
            <a-table v-if="!showtree"
                     bordered
                     ref="unitTableList"
                     :showHeader="false"
                     :pagination="unitpagination"
                     :rowKey="(record, index) => record.id"
                     :data-source="unitdata"
                     :customRow="unitTableRowClick"
                     @change="unitHandleTableChange"
                     :columns="unitcolumns">
              <template slot="cfullName"
                        slot-scope="text,record"
                        :algin="left">
                <div style="cursor: pointer;"
                     :title="record.parentName +'/'+record.fullName">
                  <span v-if="!!record.parentName">{{ record.parentName }}<span>&nbsp;/&nbsp;</span></span>{{ record.fullName }}
                </div>
              </template>
            </a-table>
            <!-- <a-table v-if="!showtree"
                     ref="unitTableList"
                     :showHeader="false"
                     :columns="unitcolumns"
                     :data-source="unitdata"
                     bordered
                     size="middle">
              <template slot="cfullName"
                        slot-scope="text,record"
                        :algin="left">
                <div style="cursor: pointer;"
                     :title="record.parentName +'/'+record.fullName">
                  <span v-if="!!record.parentName">{{ record.parentName }}<span>&nbsp;/&nbsp;</span></span>{{ record.fullName }}
                </div>
              </template>
            </a-table> -->
            <a-tree style="overflow-y: auto;height: 650px;"
                    v-if="showtree"
                    :replace-fields="unitReplaceFields"
                    :showIcon="true"
                    class="treeClass"
                    :load-data="loadUnitTree"
                    :tree-data="unitTreeData"
                    @select="unitTreeCheck">
              <a-icon slot="switcherIcon"
                      type="caret-down" />
              <a-icon slot="clazz"
                      type="appstore" />
              <a-icon slot="unit"
                      type="home" />
              <a-icon slot="dept"
                      type="bank" />
            </a-tree>
          </template>
        </div>
      </a-col>
      <a-col :span="1"
             :order="2">
        <a-divider style="height:100%;margin-left:50%"
                   type="vertical" />
      </a-col>

      <a-col :span="18"
             :order="3">
        <slot name="searchWrapper" />
        <a-form v-if="!$slots.searchWrapper"
                layout="inline">
          <a-row type="flex">
            <a-col :span="16">
              <a-space>
                <slot name="buttons" />
                <template v-if="!$slots.buttons">
                  <a-button type="primary"
                            v-if="hasPermission('add')"
                            icon="plus"
                            @click="edit()">
                    新增用户
                  </a-button>
                  <a-button type="primary"
                            v-if="hasPermission('order')"
                            icon="plus"
                            @click="orderUser()">
                    排序
                  </a-button>
                </template>
              </a-space>
            </a-col>

            <a-col :span="8">
              <a-form layout="inline">
                <a-row type="flex"
                       justify="end">
                  <a-col>
                    <slot name="search" />
                    <a-input-search v-if="!$slots.search"
                                    v-model="queryParam.keyWord"
                                    style="width: 240px"
                                    placeholder="用户姓名、账号、电话"
                                    allow-clear
                                    @search="userloadAll" />
                  </a-col>
                </a-row>
              </a-form>
            </a-col>
          </a-row>
        </a-form>
        <br>
        <slot name="table" />
        <a-table v-if="!$slots.table"
                 :columns="usercolumns"
                 ref="userTableList"
                 :rowKey="(record, index) => index"
                 :data-source="userdata"
                 @change="userHandleTableChange"
                 :pagination="userpagination">
          <template slot="userName"
                    slot-scope="text,record">
            <span :title="record.fullname">{{ record.fullname }}</span>
          </template>
          <template slot="deptFullName"
                    slot-scope="text,record">
            <span :title="record.unitFullName">{{ record.deptFullName }}</span>
          </template>
          <template slot="userAccount"
                    slot-scope="text,record">
            {{ record.account }}
          </template>
          <template slot="userTel"
                    slot-scope="text,record">
            {{ record.userTel }}
          </template>
          <template slot="orderno"
                    slot-scope="text,record">
            {{ record.orderno }}
          </template>
          <template slot="state"
                    slot-scope="text,record">
            <span v-if=" record.state == '1' ">在职</span>
            <span v-if=" record.state == '2' ">离职</span>
            <span v-if=" record.state == '3' ">删除</span>
          </template>
          <span slot="operation"
                slot-scope="text, record">
            <Zoptionitem :optiondata="optiondata"
                         :record="record"></Zoptionitem>
          </span>
        </a-table>
      </a-col>
    </a-row>
    <sync @cancel="cancel"
          :visible="syncVisible"
          :mediaType="mediaType"
          :deptId="deptId"
          :syncType="syncType"
          :mediaId="mediaId"></sync>

    <a-modal title="机构排序"
             :visible="order.visible"
             @ok="orderHandleOk"
             @cancel="orderHandleCancel">
      <a-tree style="overflow-y:auto;max-height: 500px"
              ref="unitTree"
              :showIcon="true"
              :expandedKeys="order.unit.expandedKeys"
              @expand="orderExpand"
              @drop="drop"
              :draggable="order.unit.draggable"
              :tree-data="order.unit.treeData">
        <a-icon slot="switcherIcon"
                type="caret-down" />
        <a-icon slot="clazz"
                type="appstore" />
        <a-icon slot="unit"
                type="home" />
        <a-icon slot="dept"
                type="bank" />
        <a-icon slot="user"
                type="user" />
        <template #title="item">
          <span>{{ item.treeTitle }}</span>
        </template>
      </a-tree>
    </a-modal>
  </page-card>
</template>

<script>
import Sync from '../sync/Sync'
import Zoptionitem from '../../components/z-column/Zoptionitem.vue'
import {
  userlistpage,
  unitpage,
  syncUnitTree,
  userOrderTree,
  userOrder,
  resetUserLock
} from '../../api/user/index'
import { PAGINATION } from '../../constants'

export default {
  components: { Zoptionitem, Sync },
  props: {
    optiondataProps: {
      type: Array,
      require: true,
      default: null
    }
  },
  data () {
    return {
      order: {
        unitId: '',
        visible: false,
        unit: {
          expandedKeys: [],
          treeData: [],
          draggable: true
        }
      },
      unitcolumns: [
        {
          title: '机构名称',
          dataIndex: 'name',
          align: 'left',
          ellipsis: true,
          scopedSlots: { customRender: 'cfullName' }
        }
      ],
      optiondata: [
        {
          type: 'text',
          fn: this.edit,
          title: '编辑',
          show: this.hasPermission('edit')
        },
        {
          type: 'text',
          fn: this.sync,
          title: '同步',
          show: this.hasPermission('synclog')
          // && this.syncOff
        },
        {
          type: 'text',
          fn: this.syncLog,
          title: '同步记录',
          show: this.hasPermission('synclog') && this.syncOff
        },
        {
          type: 'text',
          fn: this.change,
          title: '转岗',
          show: this.hasPermission('transfer')
        },
        {
          type: 'text',
          fn: this.addunit,
          title: '兼职',
          show: this.hasPermission('transfer')
        },
        {
          type: 'text',
          fn: this.reset,
          title: '解锁',
          show: this.hasPermission('reset')
        }
      ],
      syncOff: true,
      deptId: '',
      syncVisible: false,
      mediaType: '2',
      syncType: '',
      mediaId: '',
      unitNameOrCode: '', // 搜索条件
      unitdata: [],
      userdata: [],
      unitTreeData: [],
      unitReplaceFields: { title: 'treeTitle' },
      showtree: true,
      showaddBtn: false,
      orgId: null,
      orgType: '',
      usercolumns: [
        {
          title: '姓名',
          dataIndex: 'userName',
          align: 'left',
          ellipsis: true,
          width: '140px',
          scopedSlots: { customRender: 'userName' }
        },
        {
          title: '机构名称',
          dataIndex: 'deptFullName',
          align: 'left',
          ellipsis: true,
          width: '50%',
          scopedSlots: { customRender: 'deptFullName' }
        },
        {
          title: '账号',
          dataIndex: 'userAccount',
          align: 'center',
          ellipsis: true,
          width: '140px',
          scopedSlots: { customRender: 'userAccount' }
        },
        {
          title: '手机号码',
          dataIndex: 'userTel',
          align: 'center',
          ellipsis: true,
          width: '140px',
          scopedSlots: { customRender: 'userTel' }
        },
        {
          title: '排序号',
          dataIndex: 'orderno',
          align: 'center',
          ellipsis: true,
          width: '140px',
          scopedSlots: { customRender: 'orderno' }
        },
        {
          title: '状态',
          dataIndex: 'state',
          align: 'center',
          scopedSlots: { customRender: 'state' },
          width: '70px'
        }
      ],
      queryParam: {
        keyWord: ''
      },
      unitpagination: {
        current: 1,
        total: 0,
        pageSize: 10,
        size: 'small'
      },
      userpagination: PAGINATION
    }
  },
  beforeCreate () {
    this.syncOff =
      this.$store.getAppConfig('_syncOff') !== undefined &&
      this.$store.getAppConfig('_syncOff') == 1
  },
  created () {
    console.log(this.syncOff)
    this.initData()
    if (this.hasPermissions('edit', 'delete')) {
      this.usercolumns.push({
        title: '操作',
        dataIndex: 'operation',
        align: 'center',
        width: '30%',
        scopedSlots: { customRender: 'operation' }
      })
    }
    // 单位树未被重写时，默认加载单位树
    !this.$slots.unitTree && this.loadUnitTree()

    // 单位树及列表未被重写并且未配置路由保持，默认加载机构用户
    !this.$route.meta.keepAlive &&
      !this.$slots.unitTree &&
      !this.$slots.table &&
      this.userload()
  },
  activated () {
    // 单位树及列表未被重写并且配置了路由保持，默认加载机构用户
    this.$route.meta.keepAlive &&
      !this.$slots.unitTree &&
      !this.$slots.table &&
      this.userload()
  },
  methods: {
    initData () {
      if (this.optiondataProps) {
        this.optiondata = this.optiondataProps
      }
    },
    cancel () {
      this.syncVisible = false
    },
    reset (record) {
      resetUserLock(record.account).then((res) => {
        this.message.success('操作成功')
      })
    },
    sync (record) {
      this.deptId = record.deptId
      this.syncVisible = true
      this.mediaId = record.id
      this.syncType = '4'
    },
    syncLog (record) {
      this.$router.push({
        path: '/sync/list/detail',
        query: {
          mediaId: record.id,
          mediaType: '2'
        }
      })
    },
    unitTreeCheck (selectedKeys, info) {
      this.queryParam.secrehUnitId = info.node.dataRef.id
      this.orgId = info.node.dataRef.id
      this.orgType = info.node.dataRef.nodeType

      this.userpagination.current = 1
      this.userpagination.pageSize = 10
      this.userload()
    },
    unitTableRowClick (row) {
      return {
        on: {
          click: () => {
            this.queryParam.secrehUnitId = row.id
            this.orgId = row.id
            this.userload()
          }
        }
      }
    },
    findUnit (isInitPage = false) {
      if (!this.unitNameOrCode) {
        this.showtree = true
        this.userloadAll()
        return
      }
      if (isInitPage) {
        this.unitpagination.current = 1
      }
      this.showtree = false
      let queryParam = {}
      queryParam.currPage = this.unitpagination.current
      queryParam.pageSize = this.unitpagination.pageSize
      queryParam.name = this.unitNameOrCode
      unitpage(queryParam).then((response) => {
        if (response.list) {
          let i = 0
          for (i; i < response.list.length; i++) {
            const unit = response.list[i]
            for (const item in unit) {
              if (item === 'children') {
                delete unit[item]
              }
            }
          }
        }
        this.unitdata = response.list
        this.unitpagination.current = response.currPage
        this.unitpagination.total = response.totalCount
      })
    },
    loadUnitTree (treeNode) {
      const topId = !treeNode ? 0 : treeNode.dataRef.key
      const _this = this
      return new Promise((resolve) => {
        syncUnitTree(topId).then((response) => {
          if (treeNode) {
            treeNode.dataRef.children = response
            _this.unitTreeData = [..._this.unitTreeData]
            resolve()
          } else {
            _this.unitTreeData = response
          }
        })
      })
    },
    userloadAll () {
      // this.queryParam.secrehUnitId = ''
      this.userpagination.current = 1
      this.userload()
    },
    userload () {
      this.queryParam.currPage = this.userpagination.current ? this.userpagination.current : 1
      this.queryParam.pageSize = this.userpagination.pageSize ? this.userpagination.pageSize : 10
      userlistpage({ ...this.queryParam }).then((response) => {
        this.userdata = response.list
        this.userpagination.current = response.currPage
        this.userpagination.total = response.totalCount
        this.userpagination.pageSize = response.pageSize
        // let curr = this.userpagination.total % this.userpagination.pageSize
        // if (curr == 0 && this.userpagination.current != 1) {
        //   this.queryParam.currPage = this.userpagination.current - 1
        //   this.queryParam.pageSize = this.userpagination.pageSize
        //   this.userload2()
        // }
      })
    },
    userload2 () {
      userlistpage({ ...this.queryParam }).then((response) => {
        this.userdata = response.list
        this.userpagination.current = response.currPage
        this.userpagination.total = response.totalCount
        this.userpagination.pageSize = response.pageSize
      })
    },
    userHandleTableChange (userpagination, filters, sorter) {
      this.userpagination = userpagination
      this.userload()
    },
    unitHandleTableChange (unitpagination, filters, sorter) {
      this.unitpagination = unitpagination
      this.findUnit()
    },

    edit (row) {
      // 当未选择到部门或单位的机构时 提示
      if (!row && !this.orgId) {
        this.message.warn('请点击机构树节点，指定新增用户的单位或部门')
        return
      }
      if (!row && this.orgType == '1') {
        this.message.warn('请选择机构类型为单位或部门的机构，新增用户')
        return
      }
      const id = !row ? 0 : row.id
      this.$router.push({
        path: '/user/edit',
        query: { id, orgid: this.orgId || row.deptId }
      })
    },

    change (record) {
      this.$router.push({
        path: '/user/transfer',
        query: { id: record.id, type: 1 }
      })
    },
    addunit (record) {
      this.$router.push({
        path: '/user/transfer',
        query: { id: record.id, type: 0 }
      })
    },
    orderUser (row) {
      if (this.orgType == '1' || !this.orgId) {
        this.message.warn('请选择机构类型为单位或部门的机构进行人员排序')
        return
      }
      this.initOrderTree()
    },
    initOrderTree () {
      userOrderTree({ id: this.orgId }).then((res) => {
        if (!res || res[0].children.length == 0) {
          this.message.warn('无节点可排序')
        } else {
          this.order.unitId = this.orgId
          this.order.visible = true
          res.forEach((item) => {
            if (item.id == this.orgId) {
              item.disabled = true
            }
          })
          this.order.unit.treeData = res
          this.order.unit.expandedKeys = [this.orgId]
        }
      })
    },
    orderExpand (expanded, node) {
      this.order.unit.expandedKeys = expanded
    },
    orderHandleOk () {
      userOrder(this.order.unit.treeData[0].children).then((res) => {
        // this.message.success('保存成功')
        this.order.visible = false
        this.userload()
      })
    },
    orderHandleCancel (e) {
      this.order.visible = false
    },
    drop (info, node, dragNode, dragNodesKeys) {
      const dropKey = info.node.eventKey
      const dragKey = info.dragNode.eventKey
      if (this.order.unitId == dropKey) {
        return
      }
      const dropPos = info.node.pos.split('-')
      const dropPosition =
        info.dropPosition - Number(dropPos[dropPos.length - 1])
      const loop = (data, key, callback) => {
        data.forEach((item, index, arr) => {
          if (item.key === key) {
            return callback(item, index, arr)
          }
          if (item.children) {
            return loop(item.children, key, callback)
          }
        })
      }
      const data = [...this.order.unit.treeData]
      let dragObj

      if (info.dropToGap) {
        loop(data, dragKey, (item, index, arr) => {
          arr.splice(index, 1)
          dragObj = item
        })
        let ar
        let i
        loop(data, dropKey, (item, index, arr) => {
          ar = arr
          i = index
        })
        if (dropPosition === -1) {
          ar.splice(i, 0, dragObj)
        } else {
          ar.splice(i + 1, 0, dragObj)
        }
      }
      this.order.unit.treeData = data
    }
  }
}
</script>

<style scoped>
.ant-tree li .ant-tree-node-content-wrapper .ant-tree-title {
  color: red;
  font-size: calc(var(--font-size-20) + 30px);
}
.search-form {
  width: 100%;
}
.search-form .ant-col ant-form-item-control-wrapper {
  width: 100%;
}
</style>
